import {PlusOutlined} from '@ant-design/icons';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import type {ActionType, ProColumns} from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {Button, Divider, Drawer, message, Modal, Popover, Tag} from 'antd';
import type {SorterResult} from 'antd/es/table/interface';
import React, {useRef, useState} from 'react';
import AccountRoleDetail from './components/AccountRoleDetail';
import AddFrom from './components/AddForm';
import type {AuthRoleAddItem, AuthRoleTableListItem} from './data';
import {addAdminRole, queryAdminRoleDetail, queryAdminRoleList, removeAdminRole} from './service';
import EditForm from '@/pages/System/Auth/AuthRole/components/EditForm';

const TableList: React.FC = () => {
  const [sorter, setSorter] = useState<string>('');
  const [addModalVisible, handleAddModalVisible] = useState<boolean>(false);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [editVisible, setEditVisible] = useState<boolean>(false);
  const [clickItemId, setClickItemId] = useState<string>('');
  const [clickItem, setClickItem] = useState<AuthRoleTableListItem>();
  const actionRef = useRef<ActionType>();

  async function handleAdd(fields: AuthRoleAddItem) {
    const hide = message.loading('正在添加');
    try {
      await addAdminRole(fields);
      hide();
      message.success('添加成功');
      actionRef.current?.reload();
      handleAddModalVisible(false);
      return true;
    } catch (error) {
      hide();
      message.error('添加失败请重试！');
      handleAddModalVisible(false);
      return false;
    }
  }

  const handleRemove = async (fields: { id: string }) => {
    const hide = message.loading('正在删除');
    try {
      await removeAdminRole(fields);
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      hide();
      message.error('删除失败请重试！');
      return false;
    }
  };

  const columns: ProColumns<AuthRoleTableListItem>[] = [
    {
      title: '名称',
            dataIndex: 'name',
    },
    {
      title: '编号',
            dataIndex: 'id',
      hideInSearch: true,
      hideInTable: true,
    },
    {
      title: '权限',
            dataIndex: 'accesses',
      hideInSearch: true,
      render: (_, record) => {
        const {permissions} = record;
        if (!permissions) return null;
        const showAccesses = permissions.slice(0, 6);
        return (
            // @ts-ignore
            <Popover
                placement='topLeft'
                content={
                  <div style={{maxWidth: 300}}>
                    {permissions.map(item => (
                        <Tag style={{margin: 2}} key={item.id}>
                          {item.name}
                        </Tag>
                    ))}
                  </div>
                }
            >
              {showAccesses.map(item => (
                  <Tag key={item.id}>{item.name}</Tag>
              ))}
              {showAccesses.length < permissions.length ? '...' : ''}
            </Popover>
        );
      },
    },
    {
      title: '操作',
      //@ts-ignore
      dataIndex: 'options',
      hideInSearch: true,
      render: (_, record) => {
        const onClickDetail = () => {
          setDetailVisible(true);
          setClickItemId(record.id);
        };

        const onClickRemove = () => {
          const {id, name} = record;
          Modal.confirm({
            title: `删除角色 ${id}`,
            content: (
                <>
                  <Divider/>
                  <p>确认要删除角色</p>
                  <span
                      style={{fontWeight: 'bolder'}}>{name}</span>&nbsp;&nbsp;?
                </>
            ),
            okText: '确定',
            cancelText: '取消',
            onOk: async () => {
              await handleRemove({id});
            },
          });
        };


        return (
            <div>
              <a onClick={onClickDetail}>详情</a>
              <Divider type='vertical'/>
              <a onClick={() => {
                setEditVisible(true);
                setClickItem(record);
              }}>修改</a>
              <Divider type='vertical'/>
              <a onClick={onClickRemove}>删除</a>

            </div>
        );
      },
    },
  ];

  return (
      <PageHeaderWrapper>
        <ProTable<AuthRoleTableListItem>
            headerTitle='角色列表'
            actionRef={actionRef}
            rowKey='id'
            scroll={{x: true}}
            onChange={(_, _filter, _sorter) => {
              const sorterResult = _sorter as SorterResult<AuthRoleTableListItem>;
              if (sorterResult.field) {
                setSorter(`${sorterResult.field}_${sorterResult.order}`);
              }
            }}
            params={{
              sorter,
            }}
            toolBarRender={() => [
              <Button type='primary' onClick={() => handleAddModalVisible(true)}>
                <PlusOutlined/> 添加
              </Button>,
            ]}
            tableAlertRender={() => false}
            rowSelection={false}
            request={(params = {}) => {
              const {current: page, pageSize, ...filter} = params;
              return queryAdminRoleList({page, pageSize, ...filter});
            }}
            columns={columns}
        />
        <AddFrom
            modalVisible={addModalVisible}
            onVisibleChange={(visible => handleAddModalVisible(visible))}
            onSubmit={async (value) => {
              return await handleAdd(value);
            }}/>

        {
            clickItem && editVisible && (<EditForm
                item={clickItem}
                modalVisible={editVisible}

                onSubmit={() => {
                  setEditVisible(false);
                  setClickItem(undefined);
                  actionRef.current?.reload();
                }}
                onVisibleChange={(visible) => {
                  setEditVisible(visible);
                }}
            />)
        }


        <Drawer
            visible={!!clickItemId && detailVisible}
            onClose={() => setDetailVisible(false)}
            width='30%'
        >
          {!!clickItemId && detailVisible && (
              <AccountRoleDetail id={clickItemId}
                                 request={id => queryAdminRoleDetail({id})}/>
          )}
        </Drawer>
      </PageHeaderWrapper>
  );
};

export default TableList;
